<?php
require_once "class_Main.php";

class Form extends Main{

		protected $db_connect;
		private $to = "yourshop@gmail.com";
		private $message;
		private $subject;
		private $from;
		private $name;
		private $date = "date(d-m-Y H:i)";
		
	public function __construct($from, $name){
		$this->db_connect = parent::connect();																	//connection
		$this->data_check($from, $name);
		$this->subj();
		$this->mess();
		$this->send();
	}
	
	private function data_check($from, $name){
			$reg = "/^[a-z0-9]+[a-z0-9-_\.]*[a-z0-9]+@[a-z0-9]+([a-z0-9-_\.]*[a-z0-9]+)*\.[a-z]{2,3}$/i";
			if (preg_match($reg,$from) AND strlen($name) !== 0){
				$this->from = $from;
				$this->name = strip_tags($name);
			}
			else{
				header ("Location: ../view/form.php?error=1");
				exit;
			}
	}
	
	private function subj(){
		$this->subject = "Order #: ".mt_rand(1000,9999);
	}
	
	private function mess(){
		$message = "$this->name\n";
		$message .= "$this->subject \n\n";
		$res = "SELECT title, price FROM store WHERE bin=1 ORDER BY title ASC";
		$out = mysql_query($res, $this->db_connect) or die ("cant conectaa");
		$i=0;
		while ($row = mysql_fetch_array($out, MYSQL_NUM)){
			$data[$i] = $row;
			$i++;
		}
		foreach ($data as $value){
			$new[$i]="$value[0] - $value[1]";
			$i++;
		}
		$message .= implode("\r\n", $new);
		$this->message = $message;
	}
	
	private function send(){
			$headers = "From: $this->from\r\nReply-to: $this->from\r\nDate: $this->date\r\nContent-type: text/plain; charset: utf-8\r\n";
			mail($this->to,$this->subject,$this->message,$headers);
			header ("Location: ../index.php");
			exit;
	}
}
?>